// components/blog-ctr/blog-ctr.js
const db = wx.cloud.database();
let userInfo = {};
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    blog: Object,
    blogId: String
  },

  externalClasses: [
    "iconfont",
    "icon-pinglun",
    "icon-fenxiang"
  ],

  /**
   * 组件的初始数据
   */
  data: {
    loginShow: false, // 登陆组件是否显示
    modalShow: false, // 底部弹出层
    content: ""
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onComment(e) {
      // console.log(e);

      wx.getSetting({
        success: (res) => {
          // console.log(res);
          if (res.authSetting["scope.userInfo"]) {
            wx.getUserInfo({
              success: (res) => {
                // console.log(res);
                userInfo = res.userInfo;
                this.onLoginSuccess();
              }
            });
          } else {
            this.setData({
              loginShow: true
            })
          }
        }
      });
    },
    // 登陆成功
    onLoginSuccess() {
      this.setData({
        modalShow: true
      })
    },
    // 登陆失败
    onLoginFail() {
      wx.showModal({
        title: '授权用户才能进行评论',
        content: '',
      });
    },
    onInput(e) {
      this.setData({
        content: e.detail.value
      });
    },
    send() {
      let content = this.data.content;
      if (content.trim() == "") {
        wx.showModal({
          title: '评论内容不能为空',
          content: '',
        });
        return;
      }

      wx.showLoading({
        title: '评论中',
        mask: true
      });
      db.collection("blog-comment2")
        .add({
          data: {
            content,
            blogId: this.properties.blogId,
            nickName: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
            createTime: db.serverDate()
          }
        })
        .then((res) => {
          wx.hideLoading();
          this.setData({
            modalShow: false,
            content: ""
          });

          // 父元素刷新评论页面
          this.triggerEvent("refreshComment")
        });
    }
  }
})